<template>
  <div class="edit-wrapper-box">
    <div class="iframe-wrap" id="iframeWrap"></div>
  </div>
</template>

<script>
import { GdEditorSdk } from "@gaoding/editor-sdk";
import { gdOauth } from "@/api/gdeitor";
import { mapGetters } from "vuex";
export default {
  name: "gdEditor",
  data() {
    return {
      channelId: null, //渠道id暂时写死
      files: {}
    };
  },
  computed: {
    ...mapGetters(["userInfo"])
  },
  mounted() {
    // 进行判断 如果是非会员 那么 channelId: 191  否则为 144
    this.userInfo.memberFlag ? (this.channelId = 144) : (this.channelId = 191);
    this.getCode();
  },
  methods: {
    initSdk(thirdPartyUserCode, channelId) {
      let that = this;
      const gdEditorSDK = new GdEditorSdk({
        // 指定容器，若为空则以弹窗的方式打开
        container: ".iframe-wrap",
        // 区分编辑器类型 (图片编辑器、平面编辑器、H5编辑器)
        appId: "qiye_common_poster_editor",
        // onCompleted 执行后，是否自动关闭弹窗，默认为 true
        autoClose: false,
        // 完成按钮文案默认“完成”
        buttonText: "保存",
        // 完成下载
        onCompleted: function(obj) {
          console.log(obj);
          if (that.userInfo.memberFlag) {
            that.saveBlobAsFile(obj.blob, obj.filename);
          } else {
            that.$message({
              customClass: "noMemberTip",
              dangerouslyUseHTMLString: true,
              type: "error",
              message: `<p class="flex align-center"><img src= "/images/cry.png"/>
           <span>&nbsp;&nbsp;<font color="#35353535">抱歉，您不是会员，无法下载至本地。您可以</font><font color="#a008b2">在小程序中开通会员</font></span>
          </p>
          `
            });
          }
        },

        // 模板加载完成
        onTempletLoaded: function(editor) {
          console.log(editor);
        },

        // 关闭 SDK 或 close 调用时
        onClose: function() {}
      });
      gdEditorSDK.open({
        ext: {
          mode: "company",
          thirdCateId: channelId,
          id: this.$route.params.id, //从 海报传递过来的 稿定id,
          thirdPartyUserCode
        }
      });
    },
    getCode() {
      document.title = "秒绘作图编辑器";
      gdOauth({ uuid: this.userInfo.shortId }).then(res => {
        try {
          if (res.status) {
            this.initSdk(res.data.code, this.channelId);
          }
        } catch (error) {
          console.log(error);
        }
      });
    },
    saveBlobAsFile(blob, fileName) {
      var reader = new FileReader();
      reader.onloadend = function() {
        var base64 = reader.result;
        var link = document.createElement("a");
        document.body.appendChild(link);
        link.setAttribute("href", base64);
        link.setAttribute("download", fileName + ".png");
        link.click();
      };
      reader.readAsDataURL(blob);
    }
  }
};
</script>

<style lang="scss">
.iframe-wrap,
.edit-wrapper-box {
  height: 100%;
}
// 修改element ui默认样式--不加scoped即可
.noMemberTip {
  i {
    display: none;
  }
  img {
    width: 20px;
    height: 20px;
  }
}
</style>
